import fs from 'fs';
import path from 'path';
import * as uuid from 'uuid';
import { recursiver } from './folder.js';

export default async function (base_path, package_info, card, job, page, data) {
  const pack = {
    "ID": package_info.id,
    "Name": package_info.targetName,
    "Code": package_info.targetCode,
    "Version": package_info.version,
    "Info": package_info.description,
    "Dependencies": [],
    "Content": {
      "Cards": [],
      "Jobs": [],
      "Pages": [],
      "DataSet": {},
    },
    "Author": package_info.author,
    "ReleaseTime": new Date(),
  };

  // 本地依赖
  try {
    const depts = fs.readdirSync(path.join(base_path, 'dept'));
    depts.forEach(file => {
      if (file.toLocaleLowerCase().endsWith('.json')) {
        const txt = fs.readFileSync(path.join(base_path, 'dept', file)).toString('utf8');
        if (!txt) return;
        const dept = JSON.parse(txt);
        pack.Dependencies.push({
          ID: dept.ID,
          Name: dept.Name,
          Version: dept.Version,
        });
      }
    });
  } catch (e) {
    if (e.code !== 'ENOENT') throw e;
  }

  // npm依赖
  if (package_info.dependencies) {
    try {
      Object.keys(package_info.dependencies).forEach(name => {
        const txt = fs.readFileSync(path.join(base_path, 'node_modules', name, 'package.json'), { encoding: "utf-8" });
        const { id, targetName, version } = JSON.parse(txt);
        if (id && targetName) {
          pack.Dependencies.push({
            ID: id,
            Name: targetName,
            Version: version,
          });
        }
      });
    } catch (e) {
      if (e.code !== 'ENOENT') throw e;
    }
  }

  // 递归遍历卡片
  try {
    const fn = (name, fullname) => {
      const ext = path.extname(name);
      if (ext.toLowerCase() === '.mpcard') {
        const txt = fs.readFileSync(fullname, { encoding: "utf-8" });
        if (!txt) return;
        const card = JSON.parse(txt);
        card.开发包 = pack.ID;
        pack.Content.Cards.push(card);
      }
    };
    if (card) {
      fn(card, card);
    } else if (!card && !job && !page && !data) {
      recursiver(path.join(base_path, 'card'), fn);
    }
  } catch (e) {
    if (e.code !== 'ENOENT') throw e;
  }

  // 递归遍历作业
  try {
    const fn = (name, fullname) => {
      const file = path.parse(fullname);
      if (file.ext.toLowerCase() === '.js') {
        const js = fs.readFileSync(fullname, { encoding: "utf-8" });
        pack.Content.Jobs.push({
          "ID": newId(),
          "名称": file.name,
          "描述": null,
          "脚本": js,
          "开发包": pack.ID,
        });
      }
    };
    if (job) {
      fn(job, job);
    } else if (!card && !job && !page && !data) {
      recursiver(path.join(base_path, 'job'), fn);
    }
  } catch (e) {
    if (e.code !== 'ENOENT') throw e;
  }

  // 递归遍历数据
  try {
    const fn = (name, fullname) => {
      const file = path.parse(fullname);
      if (file.ext.toLowerCase() === '.mpdata' || file.ext.toLowerCase() === '.json') {
        const txt = fs.readFileSync(fullname, { encoding: "utf-8" });
        if (!txt) return;
        const records = JSON.parse(txt);
        pack.Content.DataSet[file.name] = records;
      }
    };
    if (data) {
      fn(data, data);
    } else if (!card && !job && !page && !data) {
      recursiver(path.join(base_path, 'data'), fn);
    }
  } catch (e) {
    if (e.code !== 'ENOENT') throw e;
  }

  // 递归遍历页面
  try {
    const fn = (name, fullname) => {
      const ext = path.extname(name);
      if (ext.toLowerCase() === '.mppage') {
        const txt = fs.readFileSync(fullname, { encoding: "utf-8" });
        if (!txt) return;
        const page = JSON.parse(txt);
        pack.Content.Pages.push({
          "ID": page.ID,
          "名称": name.replace(ext, ''),
          "描述": null,
          "类型": 'page',
          "元数据": txt,
          "开发包": pack.ID,
        });
      }
      if (ext.toLowerCase() === '.mpform') {
        const txt = fs.readFileSync(fullname, { encoding: "utf-8" });
        if (!txt) return;
        const form = JSON.parse(txt);
        pack.Content.Pages.push({
          "ID": form.ID,
          "名称": name.replace(ext, ''),
          "描述": null,
          "类型": 'form',
          "元数据": txt,
          "开发包": pack.ID,
        });
      }
    };
    if (page) {
      fn(page, page);
    } else if (!card && !job && !page && !data) {
      recursiver(path.join(base_path, 'pages'), fn);
    }
  } catch (e) {
    if (e.code !== 'ENOENT') throw e;
  }

  return pack;
}

function newId() {
  return uuid.v4().replace(/-/g, '');
}